package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.mapper.EmpLoginLogMapper;
import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.EmpLoginLog;
import com.itheima.springbootwebtlias.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

//@Aspect
@Slf4j
@Component
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.springbootwebtlias.controller.LoginController.login(com.itheima.springbootwebtlias.pojo.Emp)))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable {
        Long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            result = Result.error(e.getMessage());
        } finally {
            Long endTime = System.currentTimeMillis();
            Long costTime = endTime - startTime;

            Result result2 = (Result) result;
            Map map = (Map) result2.getData();

            String token = "";
            if (map != null) {
                token = (String) map.get("token");
            }

            int code = (Integer) result2.getCode();
            short isSuccess = (short) (code);

            Emp emp = (Emp) pjp.getArgs()[0];

            EmpLoginLog empLoginLog = new EmpLoginLog();

            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());
            empLoginLog.setIsSuccess(isSuccess);
            empLoginLog.setJwt(token);
            empLoginLog.setCostTime(costTime);

            empLoginLogMapper.insert(empLoginLog);

        }
        return result;
    }
}
